/*
 * Copyright (c) 2012 Tomas Shestakov. <http://code.google.com/p/jmmo/>
 */

package jmmo.engine.gameactor

import akka.actor.ActorRef
import jmmo.engine.property.{Identifiable, Observable, ChangeEvent, ChangeListeners}

case class ActorListener(observer: ActorRef, observable: Observable = null, eventFilter: ChangeEvent.Filter = ChangeEvent.passAll,
                                  obsFilter: Identifiable.Filter = Identifiable.passAll) extends ChangeListeners.Listener {

  override def hashCode: Int = observer.hashCode()

  def canEqual(other: Any) = other.isInstanceOf[ActorListener]

  override def equals(other: Any): Boolean = other match {
    case that: ActorListener => (that canEqual this) && observer == that.observer
    case _                   => false
  }

  def isDefinedAt(event: ChangeEvent) = eventFilter(event)

  override def apply(event: ChangeEvent) {
    if (!observer.isTerminated) {
      observer ! ObservableEvent(event.source.id, event.alteration(obsFilter), (event.chain map (_.id)): _*)
    }
    else {
      if (observable != null) {
        observable.removeChangeListener(this)
      }
    }
  }
}
